package com.chujiekeji.test.fragment;

import android.app.ProgressDialog;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chujiekeji.test.R;
import com.chujiekeji.test.account.AccountHelper;
import com.chujiekeji.test.activity.LoginActivity;
import com.chujiekeji.test.api.ChujieApi;
import com.chujiekeji.test.bean.ResultBean;
import com.chujiekeji.test.bean.User;
import com.chujiekeji.test.fragment.base.BaseFragment;
import com.chujiekeji.test.interf.OnTabReselectListener;
import com.chujiekeji.test.notice.NoticeBean;
import com.chujiekeji.test.notice.NoticeManager;
import com.chujiekeji.test.share.ShareDialog;
import com.chujiekeji.test.util.AppOperator;
import com.chujiekeji.test.util.DialogHelper;
import com.chujiekeji.test.util.TDevice;
import com.chujiekeji.test.util.ToastUtil;
import com.chujiekeji.test.util.UiUtil;
import com.chujiekeji.test.view.PortraitView;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.TextHttpResponseHandler;

import java.io.File;
import java.lang.reflect.Type;
import butterknife.BindView;
import butterknife.OnClick;
import cz.msebera.android.httpclient.Header;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * Created by fei on 2016/8/15.
 * <p>
 * 用户个人界面
 */

public class UserInfoFragment extends BaseFragment implements View.OnClickListener, NoticeManager.NoticeNotify, OnTabReselectListener {

    private ShareDialog mShareDialog;

    @BindView(R.id.iv_logo_setting)
    ImageView mIvLogoSetting;
    @BindView(R.id.iv_logo_zxing)
    ImageView mIvLogoZxing;
    @BindView(R.id.user_info_head_container)
    FrameLayout mFlUserInfoHeadContainer;

    @BindView(R.id.iv_portrait)
    PortraitView mPortrait;
    @BindView(R.id.iv_gender)
    ImageView mIvGander;
    @BindView(R.id.user_info_icon_container)
    FrameLayout mFlUserInfoIconContainer;

    @BindView(R.id.tv_nick)
    TextView mTvName;
    @BindView(R.id.tv_avail_score)
    TextView mTextAvailScore;
    @BindView(R.id.tv_active_score)
    TextView mTextActiveScore;
    @BindView(R.id.rl_show_my_info)
    LinearLayout mRlShowInfo;


    @BindView(R.id.about_line)
    View mAboutLine;

    @BindView(R.id.lay_about_info)
    LinearLayout mLayAboutCount;

    @BindView(R.id.rl_exit)
    LinearLayout exit;
    @BindView(R.id.tv_tweet)
    TextView mTvTweetCount;
    @BindView(R.id.tv_favorite)
    TextView mTvFavoriteCount;
    @BindView(R.id.tv_following)
    TextView mTvFollowCount;
    @BindView(R.id.tv_follower)
    TextView mTvFollowerCount;

    @BindView(R.id.user_info_notice_message)
    TextView mMesView;

    @BindView(R.id.user_info_notice_fans)
    TextView mFansView;

    private boolean mIsUploadIcon;
    private ProgressDialog mDialog;

    private int mMaxRadius;
    private int mR;
    private float mPx;
    private float mPy;

    private File mCacheFile;

    private User mUserInfo;

    private TextHttpResponseHandler requestUserInfoHandler = new TextHttpResponseHandler() {

        @Override
        public void onStart() {
            super.onStart();
            if (mIsUploadIcon) {
                showWaitDialog(R.string.title_updating_user_avatar);
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString
                , Throwable throwable) {
            if (mIsUploadIcon) {
                Toast.makeText(getActivity(), R.string.title_update_fail_status, Toast.LENGTH_SHORT).show();
                deleteCacheImage();
            }
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, String responseString) {
            try {
                Type type = new TypeToken<ResultBean<User>>() {
                }.getType();

                ResultBean resultBean = AppOperator.createGson().fromJson(responseString, type);
                if (resultBean.isSuccess()) {
                    User userInfo = (User) resultBean.getResult();
                    updateView(userInfo);
                    //缓存用户信息
                    AccountHelper.updateUserCache(userInfo);
                }
                if (mIsUploadIcon) {
                    deleteCacheImage();
                }
            } catch (Exception e) {
                e.printStackTrace();
                onFailure(statusCode, headers, responseString, e);
            }
        }

        @Override
        public void onFinish() {
            super.onFinish();
            if (mIsUploadIcon) mIsUploadIcon = false;
            if (mDialog != null && mDialog.isShowing()) mDialog.dismiss();
        }
    };


    /**
     * delete the cache image file for upload action
     */
    @SuppressWarnings("ResultOfMethodCallIgnored")
    private void deleteCacheImage() {
        File file = this.mCacheFile;
        if (file != null && file.exists()) {
            file.delete();
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_main_user_home;
    }

    @Override
    protected void initWidget(View root) {
        super.initWidget(root);
        measureTitleBarHeight();

        if (mFansView != null)
            mFansView.setVisibility(View.INVISIBLE);

    }

    @Override
    protected void initData() {
        super.initData();
        NoticeManager.bindNotify(this);
        requestUserCache();
    }

    @Override
    public void onResume() {
        super.onResume();
        mIsUploadIcon = false;
        if (AccountHelper.isLogin()) {
            User user = AccountHelper.getUser();
            updateView(user);
        } else {
            hideView();
        }
    }

    /**
     * if user isLogin,request user cache,
     * And then request user info and update user info
     */
    private void requestUserCache() {
        if (AccountHelper.isLogin()) {
            User user = AccountHelper.getUser();
            updateView(user);
            sendRequestData();
        } else {
            hideView();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (!AccountHelper.isLogin()) {
            hideView();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        NoticeManager.unBindNotify(this);
    }

    /**
     * update the view
     *
     * @param userInfo userInfo
     */
    private void updateView(User userInfo) {
        mPortrait.setup(userInfo);
        mPortrait.setVisibility(View.VISIBLE);

        mTvName.setText(userInfo.getNickName());
        mTvName.setVisibility(View.VISIBLE);
        mTvName.setTextSize(20.0f);
        userInfo.setGender(2);
        switch (userInfo.getGender()) {
            case 0:
                mIvGander.setVisibility(View.INVISIBLE);
                break;
            case 1:
                mIvGander.setVisibility(View.VISIBLE);
                mIvGander.setImageResource(R.mipmap.ic_male);
                break;
            case 2:
                mIvGander.setVisibility(View.VISIBLE);
                mIvGander.setImageResource(R.mipmap.ic_female);
                break;
            default:
                break;
        }

        mTextAvailScore.setVisibility(View.VISIBLE);
        mTextActiveScore.setVisibility(View.VISIBLE);
        mAboutLine.setVisibility(View.VISIBLE);
        mLayAboutCount.setVisibility(View.VISIBLE);
        if (userInfo.getStatistics()!=null){
            mTvTweetCount.setText(formatCount(userInfo.getStatistics().getTweet()));
            mTvFavoriteCount.setText(formatCount(userInfo.getStatistics().getCollect()));
            mTvFollowCount.setText(formatCount(userInfo.getStatistics().getFollow()));
            mTvFollowerCount.setText(formatCount(userInfo.getStatistics().getFans()));
        }
        exit.setVisibility(View.VISIBLE);
        mUserInfo = userInfo;
    }

    /**
     * format count
     *
     * @param count count
     * @return formatCount
     */
    private String formatCount(long count) {

        if (count > 1000) {
            int a = (int) (count / 100);
            int b = a % 10;
            int c = a / 10;
            String str;
            if (c <= 9 && b != 0)
                str = c + "." + b;
            else
                str = String.valueOf(c);

            return str + "k";
        } else {
            return String.valueOf(count);
        }

    }

    /**
     * requestData
     */
    private void sendRequestData() {
        if (TDevice.hasInternet() && AccountHelper.isLogin())
            ChujieApi.getUserInfo(requestUserInfoHandler);
    }


    /**
     *
     */
    private void hideView() {
        mPortrait.setImageResource(R.mipmap.widget_default_face);
        mTvName.setText(R.string.user_hint_login);
        mTvName.setTextSize(16.0f);
        mIvGander.setVisibility(View.INVISIBLE);
        mTextActiveScore.setVisibility(View.INVISIBLE);
        mTextAvailScore.setVisibility(View.INVISIBLE);
        mLayAboutCount.setVisibility(View.GONE);
        mAboutLine.setVisibility(View.GONE);
        exit.setVisibility(View.GONE);
    }

    /**
     * measureTitleBarHeight
     */
    private void measureTitleBarHeight() {
        if (mRlShowInfo != null) {
            mRlShowInfo.setPadding(mRlShowInfo.getLeft(),
                    UiUtil.getStatusBarHeight(getContext()),
                    mRlShowInfo.getRight(), mRlShowInfo.getBottom());
        }
    }

    @SuppressWarnings("deprecation")
    @OnClick({
            R.id.iv_logo_setting, R.id.iv_logo_zxing, R.id.iv_portrait,
            R.id.ly_tweet, R.id.ly_favorite,
            R.id.ly_following, R.id.ly_follower, R.id.rl_message,
            R.id.rl_blog, R.id.rl_read, R.id.rl_share, R.id.rl_info_tags,
            R.id.rl_info_question, R.id.rl_info_activities, R.id.rl_team,R.id.rl_exit_button
    })
    @Override
    public void onClick(View v) {

        int id = v.getId();

        if (id == R.id.iv_logo_setting) {
//            SettingActivity.show(mContext);
        } else {

            if (!AccountHelper.isLogin()) {
                LoginActivity.show(getActivity());
                return;
            }
            switch (id) {
                case R.id.iv_logo_zxing:
//                    MyQRCodeDialog dialog = new MyQRCodeDialog(getActivity());
//                    dialog.show();
                    break;

                case R.id.iv_portrait:
                    //查看头像 or 更换头像
//                    showAvatarOperation();
                    break;
                case R.id.ly_tweet:
//                    UserTweetActivity.show(getActivity(), AccountHelper.getUserId());
                    break;
                case R.id.ly_favorite:
//                    UserCollectionActivity.show(getActivity());
                    break;
                case R.id.ly_following:
//                    UserFollowsActivity.show(getActivity(), AccountHelper.getUserId());
                    break;
                case R.id.ly_follower:
//                    UserFansActivity.show(getActivity(), AccountHelper.getUserId());
                    break;
                case R.id.rl_message:
//                    UserMessageActivity.show(getActivity());
                    break;
                case R.id.rl_blog:
//                    UserBlogActivity.show(mContext, AccountHelper.getUserId());
                    break;
                case R.id.rl_info_question:
//                    UIHelper.showUserQuestion(getActivity(), AccountHelper.getUserId());
                    break;
                case R.id.rl_info_activities:
//                    UserEventActivity.show(mContext, AccountHelper.getUserId(), "");
                    break;
                case R.id.rl_team:
//                    UIHelper.showTeamMainActivity(getActivity());
                    break;
                case R.id.rl_read:
//                    ReadHistoryActivity.show(mContext);
                    break;
                case R.id.rl_info_tags:
//                    UserTagsActivity.show(mContext);
                    break;
                case R.id.rl_share:
                    if (mShareDialog == null) {
                        mShareDialog = new ShareDialog(mContext);
                        String title = "开发者必备的手机 App，网罗全网技术内容";
                        mShareDialog.setTitle(title);
                        mShareDialog.init(getActivity(), title, "开源中国 App 4.0 全新上线，全网技术内容一手搞定，只关注我感兴趣的内容，点我查看详细介绍", "https://www.oschina.net/app_phone");
                        mShareDialog.setShareApp(true);
                    }
                    mShareDialog.show();
                    break;
                case R.id.rl_exit_button:
                    AccountHelper.logout(getView(), new Runnable() {
                        @Override
                        public void run() {
                            hideView();
                        }
                    });
                    break;
                default:
                    break;
            }
        }
    }


    /**
     * take photo
     */

    public ProgressDialog showWaitDialog(int messageId) {
        String message = getResources().getString(messageId);
        if (mDialog == null) {
            mDialog = DialogHelper.getProgressDialog(getActivity(), message);
        }

        mDialog.setMessage(message);
        mDialog.show();

        return mDialog;
    }

    /**
     * update the new picture
     */
    private void uploadNewPhoto(File file) {
        // 获取头像缩略图
        if (file == null || !file.exists() || file.length() == 0) {
            ToastUtil.showShortToast(getString(R.string.title_icon_null));
        } else {
            mIsUploadIcon = true;
            this.mCacheFile = file;
            ChujieApi.updateUserIcon(file, requestUserInfoHandler);
        }

    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions
            , @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onNoticeArrived(NoticeBean bean) {
        if (mMesView != null) {
            int allCount = bean.getReview() + bean.getLetter() + bean.getMention();
            mMesView.setVisibility(allCount > 0 ? View.VISIBLE : View.GONE);
            mMesView.setText(String.valueOf(allCount));
        }
        if (mFansView != null) {
            int fans = bean.getFans();
            mFansView.setVisibility(fans > 0 ? View.VISIBLE : View.GONE);
            mFansView.setText(String.valueOf(fans));
        }
    }


    @Override
    public void onTabReselect() {
        sendRequestData();
    }

}
